package com.wqiuqiu.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wqiuqiu.common.PageUtils;
import com.wqiuqiu.common.constant.EsConstant;
import com.wqiuqiu.common.constant.ProductConstant;
import com.wqiuqiu.common.to.es.SkuEsModel;
import com.wqiuqiu.gulimallsearch.config.GulimallElasticsearchConfig;
import com.wqiuqiu.gulimallsearch.service.MallSearchService;
import com.wqiuqiu.gulimallsearch.vo.SearchParam;
import com.wqiuqiu.gulimallsearch.vo.SearchResult;


import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.bouncycastle.pqc.asn1.ParSet;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchSortValues;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult getPageData(SearchParam param) {

        //准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        SearchResult searchResult = null;
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
            //处理返回数据
            searchResult = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;

    }

    /**
     * 根据es的返回结果，封装成页面想要的数据
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult searchResult = new SearchResult();
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        if (hits != null && hits.length > 0) {
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置高亮，也就是将要高亮的字段值加上高亮标签
                if (StringUtils.isNotEmpty(param.getKeyword())) {
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                skuEsModels.add(skuEsModel);
            }
        }

        //商品涉及的全部属性

        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        if (buckets != null && buckets.size() > 0) {
            for (Terms.Bucket bucket : buckets) {
                SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
                catalogVo.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                List<? extends Terms.Bucket> catalog_name_buckets = catalog_name_agg.getBuckets();
                if (catalog_name_buckets != null && catalog_name_buckets.size() > 0) {
                    catalogVo.setCatalogName(catalog_name_buckets.get(0).getKey().toString());
                }
                catalogVos.add(catalogVo);
            }
        }
        searchResult.setCatalogs(catalogVos);

        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attr_id_buckets = attr_id_agg.getBuckets();
        if (attr_id_buckets != null && attr_id_buckets.size() > 0) {
            for (Terms.Bucket bucket : attr_id_buckets) {
                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
                ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
                if (attr_name_agg.getBuckets() != null && attr_name_agg.getBuckets().size() > 0) {
                    attrVo.setAttrName(attr_name_agg.getBuckets().get(0).getKeyAsString());
                }
                ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
                List<? extends Terms.Bucket> attr_value_buckets = attr_value_agg.getBuckets();
                if (attr_value_buckets != null && attr_value_buckets.size() > 0) {
                    List<String> attr_values = attr_value_buckets.stream().map(obj -> obj.getKeyAsString()).collect(Collectors.toList());
                    attrVo.setAttrValue(attr_values);
                }
                attrVos.add(attrVo);
            }
        }

        searchResult.setAttrs(attrVos);
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brand_agg_buckets = brand_agg.getBuckets();
        if (brand_agg_buckets != null && brand_agg_buckets.size() > 0) {
            for (Terms.Bucket bucket : brand_agg_buckets) {
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
                ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
                if (brand_img_agg.getBuckets() != null && brand_img_agg.getBuckets().size() > 0) {
                    String brand_img = brand_img_agg.getBuckets().get(0).getKeyAsString();
                    brandVo.setBrandImg(brand_img);
                }
                ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
                if (brand_name_agg.getBuckets() != null && brand_name_agg.getBuckets().size() > 0) {
                    String brand_name = brand_name_agg.getBuckets().get(0).getKeyAsString();
                    brandVo.setBrandName(brand_name);
                }
                brandVos.add(brandVo);
            }
        }
        searchResult.setBrands(brandVos);


        //当前页
        searchResult.setPageNum(param.getPageNum());


        //总记录数
        long total = response.getHits().getTotalHits().value;
        searchResult.setTotal(total);
//        Page<SkuEsModel> skuEsModelPage = new Page<>(param.getPageNum(), EsConstant.PAGESIZE, total);
//        skuEsModelPage.setRecords(skuEsModels);

//        PageUtils queryPage = new PageUtils(skuEsModelPage);
        //全部商品/sku
        searchResult.setProducts(skuEsModels);
//        searchResult.setPageUtils(queryPage);
        //总页数
        searchResult.setTotalPages((int) ((total % EsConstant.PAGESIZE) != 0 ? (total / EsConstant.PAGESIZE) + 1 : total / EsConstant.PAGESIZE));

        return searchResult;
    }

    /**
     * 根据页面传递的参数，封装DSL语句，交给es搜索
     *
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchRequest searchRequest = new SearchRequest(EsConstant.PRODUCT);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // TODO 先要判断页面参数param是否合法
        // 查询query
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        if (param.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        if (param.getHasStock() != null) {
            //只有页面传递了该参数才作为查询条件，如果没有传递，就将有库存和没库存的都返回
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attr : param.getAttrs()) {
                String[] s1 = attr.split("_");
                String attrId = s1[0];
                String[] attrValues = s1[1].split(":");
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolQuery.must(QueryBuilders.termQuery("attrs.attrValue", attrValues)); //多值
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }
        searchSourceBuilder.query(boolQueryBuilder);

        //排序sort
        if (StringUtils.isNotEmpty(param.getSort())) {
            String sort = param.getSort();
            String[] s1 = sort.split("_");
            SortOrder order = s1[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s1[0], order);
        }
        //分页
        //从哪开始 (pagenum-1)*pagesize
        if (param.getPageNum() != null && param.getPageNum() > 0) {
            searchSourceBuilder.from((param.getPageNum() - 1) * EsConstant.PAGESIZE);
            searchSourceBuilder.size(EsConstant.PAGESIZE);
        }
        //高亮
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }


        //聚合
        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //品牌的子聚合
        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg").field("brandName").size(1);
        TermsAggregationBuilder brand_img_agg = AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1);
        brand_agg.subAggregation(brand_name_agg);
        brand_agg.subAggregation(brand_img_agg);
        searchSourceBuilder.aggregation(brand_agg);
        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);
        //属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(20);
        // TODO 这里在attrID下做attrName的子聚合 表示一个ID可能对于多个name ？？？ 还是只能这样 如果只有一个值，那么有必要弄个子聚合？？？
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(20));
        attr_agg.subAggregation(attr_id_agg);

        searchSourceBuilder.aggregation(attr_agg);

        searchRequest.source(searchSourceBuilder);

        String string = searchSourceBuilder.toString();
        System.out.println("创建的DSL：" + string);
        return searchRequest;
    }
}
